package devcontainer

import (
	"code.gitea.io/gitea/models/db"
	"code.gitea.io/gitea/modules/setting"
	DevcontainersVO "code.gitea.io/gitea/routers/api/devcontainer/vo"
	Result "code.gitea.io/gitea/routers/entity"
	gitea_web_context "code.gitea.io/gitea/services/context"
	devstar_devcontainer_service "code.gitea.io/gitea/services/devstar_devcontainer"
)

// ListUserDevcontainers 枚举已登录用户所有的 DevContainers
//
//		GET /api/devcontainer/user
//		请求输入参数：
//	 - page: 当前第几页（默认第1页），从1开始计数
//	 - pageSize: 每页记录数（默认值 setting.UI.Admin.DevContainersPagingNum）
func ListUserDevcontainers(ctx *gitea_web_context.Context) {

	// 1. 检查用户登录状态，若未登录则返回未授权错误
	if ctx.Doer == nil {
		Result.RespUnauthorizedFailure.RespondJson2HttpResponseWriter(ctx.Resp)
		return
	}

	// 2. 查询数据库 当前登录用户拥有写入权限的仓库
	userPage := ctx.FormInt("page")
	if userPage <= 0 {
		userPage = 1
	}
	userPageSize := ctx.FormInt("page_size")
	if userPageSize <= 0 || userPageSize > setting.UI.Admin.DevContainersPagingNum {
		userPageSize = setting.UI.Admin.DevContainersPagingNum
	}
	opts := &DevcontainersVO.SearchUserDevcontainerListItemVoOptions{
		Actor: ctx.Doer,
		PaginationOptions: db.ListOptions{
			Page:     userPage,
			PageSize: userPageSize,
		},
	}
	userDevcontainersVO, err := devstar_devcontainer_service.GetUserDevcontainersList(ctx, opts)

	if err != nil {
		resultFailed2ListUserDevcontainerList := Result.ResultType{
			Code: Result.RespFailedListUserDevcontainers.Code,
			Msg:  Result.RespFailedListUserDevcontainers.Msg,
			Data: map[string]string{
				"ErrorMsg": err.Error(),
			},
		}
		resultFailed2ListUserDevcontainerList.RespondJson2HttpResponseWriter(ctx.Resp)
		return
	}

	// 3. 封装VO
	resultListUserDevcontainersVO := Result.ResultType{
		Code: Result.RespSuccess.Code,
		Msg:  Result.RespSuccess.Msg,
		Data: userDevcontainersVO,
	}

	// 4. JSON序列化，写入输出流
	responseWriter := ctx.Resp
	resultListUserDevcontainersVO.RespondJson2HttpResponseWriter(responseWriter)
}
